import { createRouter, createWebHistory } from "vue-router";
import { otherRouter } from "@/router/other.ts";
import { routerList } from "@/router/router";
import NProgress from "nprogress"; //页面跳转进度条
import "nprogress/nprogress.css";

const router = createRouter({
  // history: createWebHashHistory(import.meta.env.BASE_URL),
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...otherRouter, ...routerList],
  // 切换路由跳转到顶部
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

//前置守卫
//@ts-ignore
router.beforeEach((to, from, next) => {
  document.title = to.meta.title as string;
  console.log(to.path);
  NProgress.start(); //开启进度条
  let token = localStorage.getItem("tokenValue");
  //根据token判断是否需要登录
  if (to.path === "/login") {
    if (token != null && token != "") {
      return next("/index");
    }
    return next();
  } else {
    if (token != null && token != "") {
      return next();
    } else {
      return next("/login");
    }
  }
});

router.afterEach(() => {
  NProgress.done(); //关闭进度条
});

// 扩展 RouteMeta 接口
declare module "vue-router" {
  interface RouteMeta {
    /**
     * 是否是管理员
     */
    isAdmin?: boolean;
    /**
     * 是否需要登录验证
     */
    requiresAuth: boolean;
  }
}

export default router;
